/**
 * 商品状态管理
 */
import { defineStore } from 'pinia';
import { productApi } from '@/api';
import { setStorage, getStorage } from '@/utils/storage';

export const useProductStore = defineStore('product', {
  state: () => ({
    // 商品分类列表
    categories: getStorage('categories', []),
    // 商品列表
    productList: [],
    // 搜索历史
    searchHistory: getStorage('searchHistory', []),
    // 当前商品详情
    currentProduct: null,
    // 最近浏览商品
    recentViewList: getStorage('recentViewList', []),
    // 收藏商品列表
    favoriteList: getStorage('favoriteList', [])
  }),
  
  getters: {
    // 获取商品分类树形结构
    categoryTree(state) {
      // 一级分类
      const parents = state.categories.filter(item => !item.parentId);
      
      // 构建树形结构
      return parents.map(parent => {
        // 查找子分类
        const children = state.categories.filter(item => item.parentId === parent.id);
        
        return {
          ...parent,
          children
        };
      });
    },
    
    // 获取商品收藏ID列表
    favoriteIds(state) {
      return state.favoriteList.map(item => item.id);
    }
  },
  
  actions: {
    // 获取商品分类
    async getCategories() {
      try {
        const res = await productApi.getCategories();
        
        if (res.code === 200 && res.categories) {
          this.categories = res.categories;
          setStorage('categories', this.categories);
          return this.categories;
        } else {
          return Promise.reject(res.msg || '获取商品分类失败');
        }
      } catch (error) {
        console.log('接口未实现，使用本地分类数据');
        
        // 使用本地存储的分类
        this.categories = getStorage('categories', []);
        
        // 如果没有本地数据，则使用模拟数据
        if (!this.categories.length) {
          const mockCategories = [
            { id: '1', name: '手机数码', icon: 'phone' },
            { id: '2', name: '电脑办公', icon: 'laptop' },
            { id: '3', name: '家用电器', icon: 'home' },
            { id: '4', name: '服装鞋包', icon: 'clothes' },
            { id: '5', name: '食品生鲜', icon: 'food' },
            { id: '6', name: '美妆护肤', icon: 'cosmetics' },
            { id: '7', name: '玩具乐器', icon: 'toy' },
            { id: '8', name: '运动户外', icon: 'sports' },
            { id: '9', name: '图书音像', icon: 'book' },
            { id: '1-1', name: '手机', parentId: '1', icon: '' },
            { id: '1-2', name: '相机', parentId: '1', icon: '' },
            { id: '1-3', name: '耳机', parentId: '1', icon: '' },
            { id: '2-1', name: '笔记本', parentId: '2', icon: '' },
            { id: '2-2', name: '平板', parentId: '2', icon: '' }
          ];
          
          this.categories = mockCategories;
          setStorage('categories', mockCategories);
        }
        
        return this.categories;
      }
    },
    
    // 获取商品列表
    async getProductList(params = {}) {
      try {
        const res = await productApi.getProductList(params);
        
        if (res.code === 200) {
          this.productList = res.products || [];
          return res;
        } else {
          return Promise.reject(res.msg || '获取商品列表失败');
        }
      } catch (error) {
        console.error('获取商品列表失败', error);
        return Promise.reject(error);
      }
    },
    
    // 获取商品详情
    async getProductDetail(id) {
      try {
        const res = await productApi.getProductDetail(id);
        
        if (res.code === 200 && res.product) {
          this.currentProduct = res.product;
          
          // 添加到最近浏览
          this.addToRecentView(res.product);
          
          return res.product;
        } else {
          return Promise.reject(res.msg || '获取商品详情失败');
        }
      } catch (error) {
        console.error('获取商品详情失败', error);
        return Promise.reject(error);
      }
    },
    
    // 添加到最近浏览
    addToRecentView(product) {
      if (!product) return;
      
      // 移除已存在的相同商品
      this.recentViewList = this.recentViewList.filter(item => item.id !== product.id);
      
      // 添加到列表开头
      this.recentViewList.unshift({
        id: product.id,
        name: product.name,
        image: product.image || product.images?.[0],
        price: product.price,
        originPrice: product.originPrice
      });
      
      // 最多保留20条记录
      if (this.recentViewList.length > 20) {
        this.recentViewList = this.recentViewList.slice(0, 20);
      }
      
      // 保存到本地存储
      setStorage('recentViewList', this.recentViewList);
    },
    
    // 清空最近浏览
    clearRecentView() {
      this.recentViewList = [];
      setStorage('recentViewList', []);
    },
    
    // 添加搜索历史
    addSearchHistory(keyword) {
      if (!keyword) return;
      
      // 移除已存在的相同关键词
      this.searchHistory = this.searchHistory.filter(item => item !== keyword);
      
      // 添加到列表开头
      this.searchHistory.unshift(keyword);
      
      // 最多保留10条记录
      if (this.searchHistory.length > 10) {
        this.searchHistory = this.searchHistory.slice(0, 10);
      }
      
      // 保存到本地存储
      setStorage('searchHistory', this.searchHistory);
    },
    
    // 清空搜索历史
    clearSearchHistory() {
      this.searchHistory = [];
      setStorage('searchHistory', []);
    },
    
    // 获取收藏商品列表
    async getFavoriteList() {
      try {
        const res = await productApi.getFavoriteList();
        
        if (res.code === 200 && res.favorites) {
          this.favoriteList = res.favorites;
          setStorage('favoriteList', this.favoriteList);
          return this.favoriteList;
        } else {
          return Promise.reject(res.msg || '获取收藏列表失败');
        }
      } catch (error) {
        console.log('接口未实现，使用本地收藏数据');
        
        this.favoriteList = getStorage('favoriteList', []);
        return this.favoriteList;
      }
    },
    
    // 添加商品收藏
    async addToFavorite(product) {
      if (!product) return Promise.reject('商品信息不能为空');
      
      try {
        const res = await productApi.addToFavorite({
          productId: product.id,
          productInfo: {
            id: product.id,
            name: product.name,
            image: product.image || product.images?.[0],
            price: product.price,
            originPrice: product.originPrice
          }
        });
        
        if (res.code === 200) {
          // 避免重复添加
          if (!this.favoriteIds.includes(product.id)) {
            const favoriteItem = {
              id: product.id,
              name: product.name,
              image: product.image || product.images?.[0],
              price: product.price,
              originPrice: product.originPrice,
              addTime: new Date().toISOString()
            };
            
            this.favoriteList.unshift(favoriteItem);
            setStorage('favoriteList', this.favoriteList);
          }
          
          return true;
        } else {
          return Promise.reject(res.msg || '收藏失败');
        }
      } catch (error) {
        console.log('接口未实现，使用本地数据添加收藏');
        
        // 避免重复添加
        if (!this.favoriteIds.includes(product.id)) {
          const favoriteItem = {
            id: product.id,
            name: product.name,
            image: product.image || product.images?.[0],
            price: product.price,
            originPrice: product.originPrice,
            addTime: new Date().toISOString()
          };
          
          this.favoriteList.unshift(favoriteItem);
          setStorage('favoriteList', this.favoriteList);
        }
        
        return true;
      }
    },
    
    // 取消商品收藏
    async removeFavorite(id) {
      try {
        const res = await productApi.removeFavorite(id);
        
        if (res.code === 200) {
          this.favoriteList = this.favoriteList.filter(item => item.id !== id);
          setStorage('favoriteList', this.favoriteList);
          return true;
        } else {
          return Promise.reject(res.msg || '取消收藏失败');
        }
      } catch (error) {
        console.log('接口未实现，使用本地数据移除收藏');
        
        this.favoriteList = this.favoriteList.filter(item => item.id !== id);
        setStorage('favoriteList', this.favoriteList);
        
        return true;
      }
    },
    
    // 清空商品收藏
    async clearFavorite() {
      try {
        const res = await productApi.clearFavorite();
        
        if (res.code === 200) {
          this.favoriteList = [];
          setStorage('favoriteList', []);
          return true;
        } else {
          return Promise.reject(res.msg || '清空收藏失败');
        }
      } catch (error) {
        console.log('接口未实现，使用本地数据清空收藏');
        
        this.favoriteList = [];
        setStorage('favoriteList', []);
        
        return true;
      }
    },
    
    // 检查商品是否已收藏
    isFavorite(id) {
      return this.favoriteIds.includes(id);
    },
    
    // 切换商品收藏状态
    async toggleFavorite(product) {
      if (this.isFavorite(product.id)) {
        return this.removeFavorite(product.id);
      } else {
        return this.addToFavorite(product);
      }
    }
  }
}); 